const express = require('express')
const multer = require('multer')
const fs = require('fs')
const promisify = require('util').promisify
const { getDb, saveDb, saveParameter, getParameter, deletePrintLog } = require('./db')
const { getTime } = require('./common')

const rename = promisify(fs.rename)

const printer = express.Router()
const upload_path = 'uploads/'
const upload = multer({ dest: upload_path })

printer.get('/history', async (req, res, next) => {
  try {
    let db = await getDb();
    res.status(200).json(db.upload)
  } catch (error) {
    next(error)
  }
})

printer.get('/parameter', async (req, res, next) => {
  try {
    let result = undefined
    if (req.body != undefined) {
      result = await getParameter()
    }
    if (result == undefined) {
      res.status(202).send('还没有设定打印参数')
    }else{
      res.json({
        data: result
      })
    }
  } catch (error) {
    next(error)
  }
})

printer.post('/parameter', async (req, res, next) => {
  try {
    // console.log('打印参数设定')
    // console.log(req.body)
    if (req.body != undefined) {
      await saveParameter(req.body)
    }
    res.json({
      data: '打印参数设定成功'
    })
  } catch (error) {
    next(error)
  }
})

printer.post('/upload', upload.single('file'), async (req, res, next) => {
  try {
    // console.log(req)
    if (req.file == undefined) {
      throw new Error('你发送一个空文件');
    }  else {
      let parameter = await getParameter()
      if (parameter == undefined) {
        res.status(202).send('请先进行打印参数设定')
      }else{
        let name = upload_path + `${req.file.originalname}`
        await rename(`${req.file.path}`, name)
        console.log('成功打印' + name)
        let time = getTime()
        let db = await getDb()
        db.upload.push({
          "ip": req.ip,
          "date": time,
          "file": `${req.file.originalname}`,
          "parameter": parameter
        })
        await saveDb(db)
        res.json({
          data: `成功收到文件: ${req.file.originalname}`
        })
      }
    }
  } catch (error) {
    next(error)
  }
})

printer.post('/finish', (req, res, next) => {
  try {
    console.log('结束打印')
    res.json({
      data: 'success'
    })
  } catch (error) {
    next(error)
  }
})

printer.delete('/history', async (req, res, next) => {
  try {
    console.log('删除历史')
    await deletePrintLog(parseInt(req.body))
    res.json({
      data: 'success'
    })
  } catch (error) {
    next(error)
  }
})

module.exports = printer